﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MetaDrive.Core
{       
    public class Pipeline : IPipeline
    {        
        private IList<IPipelineStep> steps = new List<IPipelineStep>();

        public IServiceContainer ServiceProvider { get; private set; }

        public Pipeline()
        {
            ServiceProvider = new ServiceContainer();
            ServiceProvider.SetService<IPipeline>(this);                        
        }

        public virtual bool Process()
        {
            bool result = true;

            try
            {
                foreach (IPipelineStep step in this.steps)
                {
                    step.Init(this.ServiceProvider);
                }

                foreach (IPipelineStep step in this.steps)
                {
                    result = result && step.Process();
                }
            }
            finally
            {
                foreach (IPipelineStep step in this.steps)
                {
                    step.Complete();
                }
            }

            return result;
        }
      
        public IPipeline Add(IPipelineStep step)
        {
            this.steps.Add(step);
            return this;
        }
        
        public IEnumerator<IPipelineStep> GetEnumerator()
        {
            return this.steps.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }        
    }
}
